var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const cors = require('cors');

var indexRouter = require('./routes/index');
var userRouter = require('./routes/user');
var cardRouter = require('./routes/card');
var commonRouter = require('./routes/common');


const allowList = ['localhost:3000', 'localhost:80']; // 允许跨域访问的地址
var corsOptionsDelegate = function (req, callback) {
  var corsOptions;
  if (allowList.indexOf(req.header('Origin')) !== -1) {
    corsOptions = { origin: true } // reflect (enable) the requested origin in the CORS response
  } else {
    corsOptions = { origin: false } // disable CORS for this request
  }
  callback(null, corsOptions) // callback expects two parameters: error and options
}

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use(cors({"origin": ["http://localhost", "http://localhost:3000", "http://192.168.1.9:3000", "http://192.168.1.9", "http://120.79.73.210"]}))
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

app.use('/', indexRouter);
app.use('/user', userRouter);
app.use('/card', cardRouter);
app.use('/common', commonRouter);

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  // render the error page
  const code = err.status || 500
  res.status(code);
  // res.render('error');
  return res.send({
    code,
    msg: err.message,
  })
});

module.exports = app;
